import { readFileSync, readdirSync, statSync } from 'fs';
import { extname, join, resolve } from 'path';
import ignore from 'ignore';
/** 从指定目录中提取代码并合并为一个字符串 */
export var getCode = function (
/** 需要提取的根目录 */
rootDir, config) {
    if (!config)
        config = {};
    if (!config.exts || config.exts.length == 0)
        config.exts = ['.js', '.ts', '.css', '.sass', '.scss', '.html', '.sql', '.json', '.mjs', '.mts'];
    if (!config.exclude || config.exclude.length == 0)
        config.exclude = ['package-lock.json', 'package.json', 'LICENSE', '.gitignore', '.git/', 'node_modules/', 'tsconfig.json', 'vite.config.*'];
    var files = getFiles(rootDir, config.exts, config.exclude);
    var code = '';
    var line = 0;
    files.forEach(function (file) {
        var content = readFileSync(file).toString().trim();
        var thisLine = content.split('\n').length;
        code += content + '\n';
        line += thisLine;
        if (config === null || config === void 0 ? void 0 : config.log)
            console.log(thisLine, '\t', file);
    });
    code = code.trim();
    return { code: code, line: line };
};
export var removeSpace = function (code) {
    return code.replace(/[\n\s*]+/g, '\n').trim();
};
/**
 * 遍历获取文件列表
 * @param rootDir 需要提取的根目录
 * @param exts 需要筛选的文件后缀，以 `.` 开头
 * @param exclude 排除项，使用 `.gitignore` 规则
 * @returns
 */
export var getFiles = function (rootDir, exts, exclude) {
    if (exts === void 0) { exts = []; }
    if (exclude === void 0) { exclude = []; }
    rootDir = resolve(rootDir);
    var stack = [rootDir];
    var files = [];
    var ig = ignore().add(exclude);
    while (stack.length > 0) {
        var thisDir = stack.pop();
        for (var _i = 0, _a = readdirSync(thisDir); _i < _a.length; _i++) {
            var name_1 = _a[_i];
            var subPath = join(thisDir, name_1);
            if (ig.ignores(subPath.slice(rootDir.length + 1)))
                continue;
            else if (statSync(subPath).isDirectory())
                stack.push(subPath);
            else if (exts.length > 0 && !exts.includes(extname(subPath)))
                continue;
            else
                files.push(subPath);
        }
    }
    return files;
};
